package vn.allmobile.ambnews.activities.sflash;


import vn.allmobile.ambnews.R;
import vn.allmobile.ambnews.activities.list.ListActivity;
import vn.allmobile.ambnews.activities.main.HomeActivity;
import vn.allmobile.ambnews.data.Category;
import vn.allmobile.ambnews.data.Paper;
import vn.allmobile.ambnews.network.LoadDataListener;
import vn.allmobile.ambnews.network.NetworkAPI;
import vn.allmobile.ambnews.network.NetworkChangeReceiver;
import vn.allmobile.ambnews.utils.Contants;
import vn.allmobile.ambnews.utils.GlobalApplication;
import vn.allmobile.ambnews.utils.Log;
import vn.allmobile.ambnews.utils.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.TextView;
import android.widget.Toast;

public class SFlashActivity extends Activity implements LoadDataListener {

	static int FLAGS_MAIN_ACITIVTY = 1;
	static String paper_id = "";
	static String cat_id = ""; 
	public Handler mHandle = new Handler() {
		public void handleMessage(Message paramAnonymousMessage) {
			switch (paramAnonymousMessage.what) {
			case 0:				
				SFlashActivity.this.startMainActivity();
				break;
			case 1:
				Toast.makeText(SFlashActivity.this, "Không có kết nối mạng", Toast.LENGTH_LONG)
						.show();
				break;
			case 2:
				SFlashActivity.this.startListActivity();
			default:
			}

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sflash);
		PackageInfo pInfo = null;
		try {
			pInfo = GlobalApplication._().getPackageManager().getPackageInfo(GlobalApplication._().getPackageName(), 0);
		} catch (NameNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String version = pInfo.versionName;
		TextView versiontxt = (TextView)findViewById(R.id.version);
		versiontxt.setText("version " +version );
		
		
				
		  
		
	}
	public void networkConfirm() {
        DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int which) {
                     switch (which) {
                     case DialogInterface.BUTTON_POSITIVE:
                    	 	startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
                            break;

                     case DialogInterface.BUTTON_NEGATIVE:
                    	 	Process.killProcess(Process.myPid());
                    	 	finish();
                            break;
                     }
               }
        };

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Cần có mạng cho lần chạy đầu tiên.")
                     .setPositiveButton("Cài đặt", dialogClickListener)
                     .setNegativeButton("Thoát", dialogClickListener).show();
 }
	
	protected void startListActivity() {		
		Intent localIntent = new Intent(SFlashActivity.this, ListActivity.class);	
		if(NetworkAPI._fromNotification)
		{
			localIntent.putExtra(Contants.EXTRA_LIST_TYPE, Contants.LIST_TYPE_USER);
			
		}
		startActivity(localIntent);
		finish();
		overridePendingTransition(R.anim.slide_in_right,R.anim.no_animation);				
	}
	
	protected void startMainActivity() {
		// TODO Auto-generated method stub
		// Intent localIntent = new Intent(this, MainActivity.class);
		Intent localIntent = new Intent(this, HomeActivity.class);		
		startActivity(localIntent);
		finish();
	}

	private void startReader() {
		// TODO Auto-generated method stub
		Boolean internetStatus = NetworkChangeReceiver.isConnected(true);
				
		NetworkAPI._()._loaderThread.setloadDataListener(this);
		//this._mRequest = NetworkAPI._()._loaderThread;

		Log.v("network status:" + String.valueOf(internetStatus));
		if (internetStatus == false) {
			this.mHandle.sendEmptyMessage(1);
			// change_activity();
		}		
		NetworkAPI.onSetRequest(Contants.MSG_LOAD_PAPER);		
	}


	public void onNewIntent(Intent intent)
	{
		try{
			setIntent(intent);
		}catch(Exception e){}
				
	}
	
	
	public void onResume()
	{
	      Log.v("on resume");
		  super.onResume();			  
			try{
				Intent intent = getIntent();
				// Nếu activity start khi click vào notification
				paper_id	= intent.getStringExtra("notification_category_ppid");
				cat_id = intent.getStringExtra("notification_category_catid");		
				setIntent(null);	
			}catch(Exception e){}
			TranslateAnimation localTranslateAnimation1 = new TranslateAnimation(0, 0.0F, 0, 0.0F, 1, 1.0F, 0, 0.0F);
		      localTranslateAnimation1.setInterpolator(new DecelerateInterpolator());
		      localTranslateAnimation1.setDuration(800L);	   
		      localTranslateAnimation1.setAnimationListener(new AnimationListener() {				
				@Override
				public void onAnimationStart(Animation animation) {
					// TODO Auto-generated method stub				
				}
				
				@Override
				public void onAnimationRepeat(Animation animation) {
					// TODO Auto-generated method stub				
				}
				
				@Override
				public void onAnimationEnd(Animation animation) {
					if(!NetworkChangeReceiver.isConnected(true) && PreferenceManager.isFirstTime())
					{
						networkConfirm();
					}
					else
					{
						// TODO Auto-generated method stub
						try{					
							NetworkAPI._()._preloadData = new preloadData();																	
							NetworkAPI._()._preloadData.execute();
														
						}catch(Exception e){e.printStackTrace();}
					}
					
				}
			});
		      findViewById(R.id.flash_icon).startAnimation(localTranslateAnimation1);
		      TranslateAnimation localTranslateAnimation2 = new TranslateAnimation(0, 0.0F, 0, 0.0F, 1, -1.0F, 0, 0.0F);
		      localTranslateAnimation2.setInterpolator(localTranslateAnimation1.getInterpolator());
		      localTranslateAnimation2.setDuration(localTranslateAnimation1.getDuration());
		      findViewById(R.id.baseline).startAnimation(localTranslateAnimation2);		
	}
	
	
	@Override
	public void onBackPressed() {
		Log.v("Back pressed");
		Process.killProcess(Process.myPid());  
		
	}

	public class preloadData extends AsyncTask<Void, Boolean, Boolean> {

		@Override
		protected Boolean doInBackground(Void... params) {
			// load data here						
			SFlashActivity.this.startReader();
			return true;
		}

	}
	

	@Override
	public void onPaperloadSuccess() {
		Log.v("onPaper Load Success");
		try{
			if(!(NetworkAPI._papers.size() == 0))
			{	
				NetworkAPI.onSetRequest(Contants.MSG_LOAD_USERPAPER);						
			}				
		}catch(Exception e)
		{
			e.printStackTrace();
			Log.v("load fail");			
		}
		
	}

	@Override
	public void onCategoryloadSuccess() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onListloadSuccess() {
		Log.v("on list load success");
		
		this.mHandle.sendEmptyMessage(2);
		
	}

	@Override
	public void onListloadFail() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onUserloadSuccess() {			
		//LoaderThread.loadUserData();  
	   
		NetworkAPI._readySync = true;
		
    	if(paper_id !=null && cat_id != null)
		{
			Log.v("click from notification");
			NetworkAPI._fromNotification = true;
			int i = 0;
			for(Paper pp : NetworkAPI._userListPapers)
			{				
				if(pp.getId().equals(paper_id) )
				{
					NetworkAPI._currentPaperId = paper_id;
					NetworkAPI._currentPaperIndex = i;
					int j = 0 ;
					for(Category cat : pp.getCategories() )
					{
						if(cat.getId().equals(cat_id) )
						{
							NetworkAPI._currentCategoryId = cat_id;
							NetworkAPI._currentCategoryIndex = j;
						}
						j++;
					}
				}
				i++;
			}
			setIntent(null);
			paper_id = cat_id = ""; 
			NetworkAPI.onSetRequest(Contants.MSG_LOAD_LIST);	
		    										
		}
    	else
    	{    		
    		this.mHandle.sendEmptyMessage(0);
    	}
	    
	    
        
	}
	
	
}
